package smartbell;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

import java.awt.*;

import javax.media.Buffer;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Manager;
import javax.media.Player;
import javax.swing.*;

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;

import javax.imageio.*;
import javax.media.*;
import javax.media.control.*;
import javax.media.format.*;
import javax.media.util.*;

import smartbell.Sftp;

public class Main {
	public static void main(String[] arg) throws JSchException, Exception {
		Sftp.main(arg);

		// Camera initialization
		// Create capture device
		CaptureDeviceInfo deviceInfo = CaptureDeviceManager
				.getDevice("vfw:Microsoft WDM Image Capture (Win32):0");
		Player player = Manager.createRealizedPlayer(deviceInfo.getLocator());
		player.start();

		// Wait a few seconds for camera to initialize (otherwise img==null)
		Thread.sleep(2500);

		// Camera and FTP loop
		int count = 0;
		while (count<60) {
			Thread.sleep(500);
			// Grab a frame from the capture device
			FrameGrabbingControl frameGrabber = (FrameGrabbingControl) player
					.getControl("javax.media.control.FrameGrabbingControl");
			Buffer buf = frameGrabber.grabFrame();

			// Convert frame to an buffered image so it can be processed and
			// saved
			Image img = (new BufferToImage((VideoFormat) buf.getFormat())
					.createImage(buf));
			BufferedImage buffImg = new BufferedImage(img.getWidth(null),
					img.getHeight(null), BufferedImage.TYPE_INT_RGB);
			Graphics2D g = buffImg.createGraphics();
			g.drawImage(img, null, null);

			// Overlay curent time on image
			g.setColor(Color.RED);
			g.setFont(new Font("Verdana", Font.BOLD, 16));
			g.drawString((new Date()).toString(), 10, 25);

			// Save image to disk as PNG
			ImageIO.write(buffImg, "png", new File("c:\\Users\\Aaron\\Documents\\School\\Senior\\Senior 2nd Semester\\CSE 486\\Projectwebcam.png"));

			Thread.sleep(500);
			// Put file on server
			Sftp.sftpChannel.put("C:/webcam.png",
					"/home/misc/ademing/public_html/webcam.png");
			
			count++;
		}
		
		// Stop using webcam
		player.close();
		player.deallocate();

		Sftp.sftpChannel.exit();
		Sftp.session.disconnect();
	}
}
